package cm.example.shoppingplatformspringboot.controller;


import cm.example.shoppingplatformspringboot.entity.Address;
import cm.example.shoppingplatformspringboot.entity.User;
import cm.example.shoppingplatformspringboot.service.AddressService;
import cm.example.shoppingplatformspringboot.service.UserService;
import cm.example.shoppingplatformspringboot.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cm.example.shoppingplatformspringboot.utils.ResponseUtil.generateResponse;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private AddressService addressService;

    // 检查用户信息是否完整
    private boolean isUserInfoIncomplete(@NotNull User user) {
        return user.getAccount() == null || user.getAccount().isEmpty() ||
                user.getPassword() == null || user.getPassword().isEmpty();
    }

    // 发送验证码接口
    @PostMapping("/sendCode")
    public ResponseEntity<Map<String, Object>> sendCode(@RequestParam String phone) {
        if (phone == null || phone.isEmpty()) {
            return generateResponse("error", "手机号不能为空", null);
        }
        if (phone.length() != 11 && !phone.matches("^1[3-9]\\d{9}$")) {
            return generateResponse("error", "请输入正确手机号", null);
        }

        String code = userService.sendCode(phone);
        if (code == null) {
            return generateResponse("error", "验证码发送过于频繁，请稍后再试", null);
        }

        return generateResponse("success", "验证码已发送", code);
    }

    // 手机验证码登录接口
    @PostMapping("/loginByPhone")
    public ResponseEntity<Map<String, Object>> loginByPhone(
            @RequestParam String phone, @RequestParam String code, @RequestParam String last_login_ip) {
        // 查找用户
        User user = userService.loginByPhone(phone, last_login_ip);
        if (user == null) {
            return generateResponse("error", "用户不存在,请前往注册", null);
        }

        // 验证验证码
        if (!userService.verifyCode(phone, code)) {
            return generateResponse("error", "验证码错误或已过期", null);
        }
        // 转化用户状态（0冻结，1正常，拉黑，3不存在）
        String status = user.getStatus();
        // 转换状态描述
        String statusDesc = "0".equals(status) ? "冻结" :
                "1".equals(status) ? "正常" :
                        "2".equals(status) ? "拉黑" : "不存在";
        if (!"正常".equals(statusDesc) && !"冻结".equals(statusDesc)) {
            return generateResponse("error", "用户已" + statusDesc + ",无法登录", null);
        }

        // 生成JWT Token
        String token = JwtUtil.generateToken(user);
        // 创建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("info", user);
        return generateResponse("success", "登录成功", data);
    }

    //进行登录请求
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> loginUser(@RequestBody User user) {
        if (isUserInfoIncomplete(user)) {
            return generateResponse("error", "请填写完整的信息", null);
        }

        User hasUser = userService.login(user.getAccount(), user.getPassword(), user.getLast_login_ip());
        if (hasUser == null) {
            return generateResponse("error", "账号或密码错误", null);
        }
        // 转化用户状态（0冻结，1正常，拉黑，3不存在）
        String status = hasUser.getStatus();
        // 转换状态描述
        String statusDesc = "0".equals(status) ? "冻结" :
                "1".equals(status) ? "正常" :
                        "2".equals(status) ? "拉黑" : "不存在";
        if (!"正常".equals(statusDesc) && !"冻结".equals(statusDesc)) {
            return generateResponse("error", "用户已" + statusDesc + ",无法登录", null);
        }

        // 生成JWT Token
        String token = JwtUtil.generateToken(hasUser);

        // 创建返回数据，包含用户信息和 token
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("info", hasUser);  // 添加用户的全部信息
        return generateResponse("success", "登录成功", data);
    }

    // 注册用户
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> registerUser(@RequestBody User user) {
        // 1. 参数校验
        if (isUserInfoIncomplete(user)) {
            return generateResponse("error", "请填写完整的信息", null);
        }
        if (!user.getTelphone().matches("^1[0-9]\\d{9}$")) {
            return generateResponse("error", "请输入正确手机号", null);
        }
        if (!user.getEmail().matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$")) {
            return generateResponse("error", "邮箱格式不正确", null);
        }

        // 2. 调用注册服务
        int result = userService.registerUser(user);
        if (result == 1) {
            return generateResponse("success", "注册成功", null);
        } else if (result == 0) {
            return generateResponse("error", "账号已存在", null);
        } else if (result == 2) {
            return generateResponse("error", "手机号已注册", null);
        } else if (result == 3) {
            return generateResponse("error", "邮箱已绑定", null);
        } else {
            return generateResponse("error", "服务器繁忙，请稍后再试", null);
        }
    }


    // 获取用户信息
    @GetMapping("/info/{userId}")
    public User getUserInfo(@PathVariable Integer userId) {
        return userService.getUserInfo(userId);
    }

    // 更新用户信息
    @PutMapping("/info")
    public int updateUserInfo(@RequestBody User user) {
        return userService.updateUserInfo(user);
    }

    // 获取用户地址列表
    @GetMapping("/{userId}/addresses")
    public List<Address> getUserAddresses(@PathVariable Long userId) {
        return addressService.getUserAddresses(userId);
    }

    // 添加地址
    @PostMapping("/{userId}/addresses")
    public int addAddress(@PathVariable Long userId, @RequestBody Address address) {
        address.setUser_id(userId);
        return addressService.addAddress(address);
    }

    // 更新地址
    @PutMapping("/{userId}/addresses/{addressId}")
    public int updateAddress(@PathVariable Long userId, @PathVariable Long addressId, @RequestBody Address address) {
        address.setId(addressId);
        address.setUser_id(userId);
        return addressService.updateAddress(address);
    }

    // 删除地址
    @DeleteMapping("/addresses/{id}")
    public ResponseEntity<?> deleteAddress(@PathVariable Long id) {
        try {
            int result = addressService.deleteAddress(id);
            if (result > 0) {
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.status(404).body("地址不存在或删除失败");
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body("删除地址时出错：" + e.getMessage());
        }
    }
}


